package com.bolt.admin.module.sys.service;

import com.bolt.common.io.DirectoryUtil;
import com.bolt.common.io.FileUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.data.PageInfo;
import com.bolt.convention.exception.ServiceException;
import com.bolt.support.codegenerator.db.AbstractTableFactory;
import com.bolt.support.codegenerator.db.TableFactory;
import com.bolt.support.codegenerator.dto.TableInfo;
import com.bolt.support.codegenerator.model.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author michao
 *         Created by michao on 2018/2/7.
 */
@Component
public class CodeGeneratorService implements InitializingBean {

    private static Logger logger = LoggerFactory.getLogger(CodeGeneratorService.class);

    @Autowired
    protected ServletContext servletContext;

    @Autowired
    private MenuService menuService;


    public static final String CONTEXT_PATH = "base";

    public static final String ROOT_PATH = "classpath:/templates";

    public static final String RESOURCE_PATTERN = "/*.xml";


    @Value("${jdbc.jdbcUrl}")
    private String url;

    @Value("${jdbc.user}")
    private String username;

    @Value("${jdbc.pwd}")
    private String password;

    @Value("${jdbc.driverClass}")
    private String driverClass;


    private TableFactory tableFactory;


    public PageInfo<TableInfo> findTable(Pageable pageable, String tableName) {
        try {
            return tableFactory.getTables(tableName, (int) pageable.getOffset(), pageable.getPageSize());
        } catch (Exception ex) {
            throw new ServiceException(ex);
        }
    }


    public Table getTable(String tableName) {
        try {
            return tableFactory.getTable(tableName);
        } catch (SQLException ex) {
            logger.error("find table " + tableName + "no found", ex);
            throw new ServiceException(ex);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        tableFactory = AbstractTableFactory.getInstance(url, username, password, driverClass);
    }


    /**
     * 取包名
     *
     * @return
     */
    public Map <String, String> loopAllEntityPackage() {
        Map <String, String> packageNameSelectData = new LinkedHashMap <>();
        List <File> packages = DirectoryUtil.loopDirs("", "entity*");
        for (File dir : packages) {
            String path = dir.getPath();
            path = StrUtil.subSuf(path, path.indexOf("com"));
            String name = path.replace(File.separator, ".");
            packageNameSelectData.put(name, name);
        }
        return packageNameSelectData;
    }

    /***
     * 取类名
     * @param packageName
     * @return
     */
    public List <String> filterAllEntityName(String packageName) {
        List <String> entityName = new ArrayList <>();
        String packageDirName = packageName.replace('.', '/');
        Path path = Paths.get("", packageDirName);
        File[] javaFile = DirectoryUtil.local(path.toString(), ".*\\.java");
        for (File file : javaFile) {
            entityName.add(FileUtil.getPainFileName(file.getName(), " entity"));
        }
        return entityName;
    }

}
